import numpy as np
import matplotlib.pyplot as plt
import sys
import caffe
import os

def Build_Face_Net(cf,md,mw):
    plt.rcParams['figure.figsize'] = (10,10)
    plt.rcParams['image.interpolation'] = 'nearest'
    plt.rcParams['image.cmap'] = 'gray'
    caffe_root=cf
    sys.path.insert(0, caffe_root+'python')
    caffe.set_mode_cpu()
    model_def=md
    model_weights=mw
    mean_data=np.array([129.1863,104.7624,93.5940])
    net = caffe.Net(model_def, model_weights, caffe.TEST)
    transformer = caffe.io.Transformer({'data':net.blobs['data'].data.shape})
    transformer.set_transpose('data', (2,0,1))
    transformer.set_mean('data',mean_data)
    transformer.set_raw_scale('data', 255)
    transformer.set_channel_swap('data', (2,1,0))
    return (transformer,net)

def FaceRecognice(tf,nt,img_path):
    transformer=tf
    net=nt
    image = caffe.io.load_image(img_path)
    transformed_image = transformer.preprocess('data', image)
    net.blobs['data'].data[...] = transformed_image
    output = net.forward()
    prob = output['prob'][0]
    lst=[]
    for i in range(1,6):
        lst.append(prob.argsort()[-i])
    return lst

# caffe_root = 'C:/Program Files/caffe/caffe-master/caffe-master'
# model_def='F:/face-recognition/vgg_face_caffe/vgg_face_caffe/VGG_FACE_deploy.prototxt'
# model_weights='F:/face-recognition/vgg_face_caffe/vgg_face_caffe/VGG_FACE.caffemodel'
# tf,nt=Build_Net(caffe_root,model_def,model_weights)
# # iph='F:/face-recognition/age_gender/3.jpg'
# # r=FaceRecognice(tf,nt,iph)
# # print r
# search_dir='F:/IMS/test_photos/cut/'
# target_jpg='F:/IMS/test_photos/cut/ta1.jpg'
# tj=FaceRecognice(tf,nt,target_jpg)
# img_type=('.jpg','.PNG','.png','.JPG')
# img_list=[]
# for root,dirs,files in os.walk(search_dir):
#     for file in files:
#         if (os.path.splitext(file)[1] in img_type):
#             img_list.append(os.path.join(root,file).replace('\\','/'))
# fr=[]
# for f in img_list:
#     r=FaceRecognice(tf,nt,f)
#     cnt=0
#     for i in tj:
#         if (i in r):
#             cnt=cnt+1
#     if(cnt>1):
#         fr.append(f)
#     print f,' is finished...'
# print fr